//
//  YUYARegisterPwdViewController.m
//  com.yigu.yuya
//
//  Created by hxp on 16/3/4.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIRegisterPwdViewController.h"
#import "YAYIEidtPersonalInfoViewController.h"
#import "YAYILoginViewController.h"


//#import "User.h"
@interface YAYIRegisterPwdViewController ()
@property (nonatomic,strong)UILabel *textFieldBackground;
@property (nonatomic,strong)UITextField *PasswordTextField;
@property (nonatomic,strong)UIButton *nextBtn;
@property (nonatomic,strong)UIButton *backBtn;
@end

@implementation YAYIRegisterPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.titleStr;
    self.view.backgroundColor = [UIColor whiteColor];


    [self  createViews]; 
}


-(void)createViews{
    if (self.textFieldBackground == nil) {
        self.textFieldBackground = [UILabel new];
        self.textFieldBackground.layer.cornerRadius = 2;
        self.textFieldBackground.layer.masksToBounds = YES;
        self.textFieldBackground.layer.borderWidth = 0.5;
        self.textFieldBackground.layer.borderColor = [UIColor  lightGrayColor].CGColor;
        [self.view  addSubview:self.textFieldBackground];
    }
    [self.textFieldBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(30 + 64));
        make.left.equalTo(@17);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - 17 * 2, 40));
    }];
    
    if (self.PasswordTextField == nil) {
        self.PasswordTextField = [UITextField  new];
        self.PasswordTextField.borderStyle = UITextBorderStyleNone;
        self.PasswordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.PasswordTextField.secureTextEntry = YES;
        self.PasswordTextField.placeholder = @"6 - 16位密码";
        self.PasswordTextField.font = [UIFont systemFontOfSize:13];
        [self.view addSubview:self.PasswordTextField];
    }
    [self.PasswordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.textFieldBackground.mas_top).with.offset(5);
        make.left.equalTo(@35);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - 2 * 35, 35));
    }];
    if (self.nextBtn == nil) {
        self.nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.nextBtn setBackgroundImage:[UIImage  imageNamed:@"register_button_normal"] forState:UIControlStateNormal];
        [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [self.nextBtn setTitleColor:[UIColor  whiteColor] forState:UIControlStateNormal];
        [self.nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.nextBtn];
    }
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.PasswordTextField.mas_bottom).with.offset(128);
        make.left.mas_equalTo(self.textFieldBackground.mas_left);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - 17 * 2, 40));
    }];
}

/**
 *  注册设置密码
 */
-(void)createRegister{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *versionStr = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    /** 
     private String mobile;//手机号
     private String password;//密码
     private Byte role;//用户角色  1:病人  2:医生
     private String deviceid;//设备id
     private int systemid;//设备类型   1:安卓   2:IOS
     private String versions;//版本号 1.00
     */
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"mobile"] = self.mobile;
    param[@"password"] = self.PasswordTextField.text;
    param[@"role"] = @(2);
//    param[@"deviceid"] = [CloudPushSDK getDeviceId];
    param[@"systemid"] = @(2);
    param[@"versions"] = versionStr;

    YAYILog(@"param:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:registerUser_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        if (error == nil) {
            
            YAYILog(@"注册返回：%@", dict);
            
            NSString *message = dict[@"message"];
            if([dict[@"status"] isEqualToString:@"success"]) {
                
//                [self createHudView:message];
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", message]];
                [self userLlogin];
            }else{
                
//                [self createHudView:message];
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", message]];
                return;
            }
        }else{
            NSString *message = responseError[@"message"];
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}


/**
 *  重新设置密码
 */
-(void)resetPassword{
    
    [YAYINetWorking postJsonSerilizeWithURL:forgetPwd_url param:@{@"mobile":self.mobile,@"password":self.PasswordTextField.text,@"role":@"2"} finish:^(NSData *data, NSDictionary *dict, NSError *error, NSDictionary *responseError) {
        if (error == nil) {
            NSString *status = dict[@"status"];
            NSString *message = dict[@"message"];
            if ([status isEqualToString:@"success"]) {
                [self createHudView:message];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
                
            }else {
                [self createHudView:message];
                return;
            }
            
        }else{
            NSString *message = responseError[@"message"];
            [self createHudView:message];
        }

    }];
    
}


/** 用户登录
 *
 */
-(void)userLlogin{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *versionStr = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"mobile"] = self.mobile;
    param[@"password"] = self.PasswordTextField.text;
//    param[@"deviceid"] = [CloudPushSDK getDeviceId];
    param[@"systemid"] = @"2";
    param[@"versions"] = versionStr;
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:userLogin_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        if (error == nil) {
           
            if (error == nil) {
                NSString *message = dict[@"message"];
                NSString *status = dict[@"status"];
                if ([status isEqualToString:@"fail"]) {
                    [self createHudView:message];
                    return ;
                }else{
                    
                    // 即时聊天登录
                    
                    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                    for (int i = 0;  i < cookieJar.cookies.count; i ++) {
                        NSHTTPCookie *cookie = [cookieJar cookies][i];
                        
                        if (i == cookieJar.cookies.count - 1) {

                            NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
                            [userdef setValue:cookie.value forKey:YAYILoginCookieKey];
                            [userdef synchronize];
                        }
                    }
                    
                    YAYIEidtPersonalInfoViewController *ctl = [[YAYIEidtPersonalInfoViewController alloc] init];
                    [self.navigationController pushViewController:ctl animated:YES];
                    
                    // 登录状态改变
                    [YAYILoginViewController loginStateChanged:YAYILoginStateLogin];
                }
                
            }
            
        }else{
            NSString *message = responseError[@"message"];
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
    
    
}


#pragma mark - 响应事件
/**
 * 下一步
 */
-(void)nextAction:(UIButton *)sender
{
    if (!self.PasswordTextField.text.length || self.PasswordTextField.text.length == 0) {
        
        [SVProgressHUD showImage:nil status:@"\n\n密码不能为空\n\n"];
        return;
    };
    
    // 判断密码是否是 6 到 16位
    if (self.PasswordTextField.text.length < 6) {
        
//        [self createHudView:@"新密码长度不能少于6位"];
        [SVProgressHUD showImage:nil status:@"\n\n新密码长度不能少于6位\n\n"];
        return;
    }else if (self.PasswordTextField.text.length > 16){
        
//        [self createHudView:@"新密码长度不能大于16位"];
        [SVProgressHUD showImage:nil status:@"\n\n新密码长度不能大于16位\n\n"];
        return;
    }

    if ([self.titleStr isEqualToString:@"新密码"]) {
       [self.PasswordTextField resignFirstResponder];
       [self resetPassword];
    }else{
        [self.PasswordTextField resignFirstResponder];
        [self createRegister];
    }
    
}


/**
 * 返回
 */
-(void)backAction:(UIButton *)sender{
    [self dismissViewControllerAnimated:NO completion:nil];
}


#pragma mark  - 工具方法


-(void)createHudView:(NSString *)msg
{
    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
    [self.view addSubview:hud];
    
    [hud setMessage:msg];
    [hud removeFromSuperview:YES time:2 isHinden:YES];
}



@end
